#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include "tlogger.h"
#include "ttools.h"
#ifdef WIN32
#include <windows.h>
#else
#endif
namespace tlib
{
	TLogger g_log;
	TLogger::TLogger()
	{
		logFileTime_ = 0;
		logFile_ = NULL;
		tlib::GetExeName(filePath_, 256);
	}

	TLogger::~TLogger()
	{
		if (logFile_)
		{
			fclose(logFile_);
			logFile_ = NULL;
		}
	}

	void TLogger::OpenFile(char* file)
	{

		if (logFile_)
		{
			fclose(logFile_);
			logFile_ = NULL;
		}
		logFile_ = fopen(file, "a + ");
		fprintf(logFile_, "\n\n");
		fprintf(logFile_, "====================================================\n");
		fprintf(logFile_, "====================STARTRUN========================\n");
		fprintf(logFile_, "====================================================\n");
		fprintf(logFile_, "\n\n");
	}

	void TLogger::WriteLog(const char* level, const char* fmt, ...)
	{
		std::lock_guard<std::mutex> lock(mutex_);
		va_list args;
		va_start(args, fmt);
		vsprintf(writeBuf_, fmt, args);
		va_end(args);

		time_t atimer = time(NULL);
		struct tm* area = localtime(&atimer);
		int time = ((area->tm_year + 1900) * 100)
			+ ((area->tm_mon + 1) * 10000)
			+ (area->tm_mday * 100)
			+ area->tm_hour;

		if (logFileTime_ < time)
		{
			logFileTime_ = time;
			char file[256];
			sprintf(file, "%s.%04d%02d%02d%02d.log", filePath_, area->tm_year + 1900, area->tm_mon + 1, area->tm_mday, area->tm_hour);
			OpenFile(file);
		}
		fprintf(logFile_, "%04d-%02d-%02d %02d:%02d:%02d TID:%05d %5s - %s\n", area->tm_year + 1900, area->tm_mon + 1, area->tm_mday, area->tm_hour, area->tm_min, area->tm_sec, CurrThreadId(), level, writeBuf_);
		fflush(logFile_);
#define _TLOGGER_PRINTF_
#ifdef	_TLOGGER_PRINTF_
		printf("%04d-%02d-%02d %02d:%02d:%02d TID:%05d %5s - %s\n", area->tm_year + 1900, area->tm_mon + 1, area->tm_mday, area->tm_hour, area->tm_min, area->tm_sec, CurrThreadId(), level, writeBuf_);
#endif
	}
}